<template>
  <div>
    <el-dialog :title="title" :visible="visible" @close="handleClose" width="800px">
      <el-form :model="form" label-position="right" ref="formRef" :rules="rules">
        <el-form-item prop="name" label="类型名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" placeholder="请输入类型名称"></el-input>
        </el-form-item>
        <el-form-item prop="tag" label="类型简称" :label-width="formLabelWidth">
          <el-input v-model="form.tag" placeholder="请输入类型简称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addBasicStoShelf,editBasicStoShelf} from '@/api/index/warehouse.js'
  export default {
    data() {
      return {
        title:'新增类型',
        form: {
          name: '',
          tag:'',
          layerCount:'',
          positionsPerLayer:''
        },
        formLabelWidth: '80px',
        rules:{
          name: [{
            required: true,
            message: '类型名称不能为空',
            trigger: 'blur'
          }],
          tag: [{
            required: true,
            message: '类型简称不能为空',
            trigger: 'blur'
          }],
        }
      }
    },
    components: {

    },
    props: {
      visible: { // 接收父组件通过sync传递的visible属性
        type: Boolean,
        default: false
      },
    },
    methods: {
      openDialog(type, val) {
        this.title = type === 'edit' ? '编辑类型' : '新增类型';
        // 根据类型区分新增和编辑逻辑
        if (type === 'edit' && val) {
          this.form = {
            ...val
          };
        } else {
          this.form = {
            name: '',
            tag:'',
          };
        }
      },
      // 提取重置表单的逻辑
      handleClose() {
        // 通过事件通知父组件更新visible值，触发update:visible事件
        this.$emit('update:visible', false);
        this.$nextTick(() => {
          this.$refs.formRef.resetFields();
        })
      },
      //提交表单
      submit() {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            const apiMethod = this.title === '新增类型' ? addBasicStoShelf : editBasicStoShelf;
            // 调用相应的 API 方法
            apiMethod(this.form).then(res => {
              if (res.code == 200) {
                this.$emit('addSuccess'); // 通知父组件添加成功
                this.$message({
                  message: res.msg, // 显示成功消息
                  type: 'success',
                });
                // 提交成功后可以选择清空表单
                this.handleClose();
              }
            }).catch(err => {
              this.$message({
                message: err?.msg || '操作失败', // 捕获错误信息
                type: 'error',
              });
            });
          } else {
            // 校验失败
            return false;
          }
        });
      }
    }
  }
</script>

<style></style>
